import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/dms_file_odoo_api.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/udt_tb_docmentstock_odoo_api.dart';
import 'package:flutter_admin/constants/constant_dict.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/dms_file.dart';
import 'package:flutter_admin/models/odoo/udt_tb_docmentstock.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/udt_tb_docmentstock_dialog.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/udt_tb_docmentstock_edit.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/lend_or_return.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/utils/utils.dart';

import 'select_docmentstock_dialog.dart';


class SelectDocmentstockList extends StatefulWidget {

  List<DmsFile> dmsfiles;
  SelectDocmentstockList({Key? key,required this.dmsfiles}) : super(key: key);

  @override
  _SelectDocmentstockListState createState() => _SelectDocmentstockListState();
}

class _SelectDocmentstockListState extends State<SelectDocmentstockList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page = PageModel(orders: [OrderItemModel(column: 'id',asc: false)]);
  UdtTbDocmentstock udtTbDocmentstock = UdtTbDocmentstock();
  late List<DmsFile> dmsfiles;
  List<UdtTbDocmentstock> selectedList = [];
  //文档类别
  late List<SelectOptionVO> docmenttypeList = [];
  @override
  void initState() {
    dmsfiles = widget.dmsfiles;
    var deparment = StoreUtil.read(Constant.KEY_CURRENT_USER_INFO)[0]["department_id"];
    udtTbDocmentstock.departmentId = deparment[0].toString();
    udtTbDocmentstock.departmentName = deparment[1].toString();
    // udtTbDocmentstock.documentno
    _loadSelectVO();
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  _loadSelectVO() async{
    docmenttypeList = await DynamicDataApi.getModelSelect(active:false,model: "dms.documenttype",name: "documenttypename",key: "department_id",val: int.parse(udtTbDocmentstock.departmentId!));
    setState(() { });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 280,
            label: '所属部门',
            enable: false,
            value: udtTbDocmentstock.departmentName,
          ),
          CrySelect(
            width: 280,
            label: '档案项目',
            dataList: docmenttypeList,
            value: udtTbDocmentstock.documenttypeId,
            onSaved: (v) => {udtTbDocmentstock.documenttypeId = v},
          ),
          CryInput(
            width: 280,
            label: '档案盒名称',
            value: udtTbDocmentstock.documentname,
            onSaved: (v) {
              udtTbDocmentstock.documentname = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [ _operationList(), ] : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map<String, dynamic> selected) {
        this.setState(() {});
        _fileTransfer(selected);
      },
      columns: [
        // isDisplayDesktop(context)
        //     ? DataColumn(
        //         label: Text(S.of(context).operating),
        //       )
        //     : DataColumn(label: Container()),
        DataColumn(
          label: Text('档案盒编号'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('档案盒名称'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('档案项目'),
          // onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
      ],
      getCells: (m) {
        UdtTbDocmentstock udtTbDocmentstock = UdtTbDocmentstock.fromMap(m);
        return [
          DataCell(Text(udtTbDocmentstock.documentno ?? '--')),
          DataCell(Text(udtTbDocmentstock.documentname ?? '--')),
          DataCell(Text(udtTbDocmentstock.documenttypeName ?? '--')),
        ];
      },
    );
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            final ScaffoldState? scaffold = Scaffold
                .maybeOf(context);
            final ModalRoute<Object?>? parentRoute = ModalRoute.of(context);
            final bool canPop = parentRoute?.canPop ?? false;

            if (canPop) {
              return BackButton();
            } else {
              return SizedBox.shrink();
            }
          },
        ),
        title: Text('文档转移'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() {
    udtTbDocmentstock = UdtTbDocmentstock();
    var deparment = StoreUtil.read(Constant.KEY_CURRENT_USER_INFO)[0]["department_id"];
    udtTbDocmentstock.departmentId = deparment[0].toString();
    udtTbDocmentstock.departmentName = deparment[1].toString();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await UdtTbDocmentstockOdooApi.page(
        data: {"page": page, "domainList": udtTbDocmentstock.toDomainList(),},isSelect: true,documentno: dmsfiles[0].documentno);

    if(responseBodyApi.success!){
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
    }
  }

  _sort(column, {ascending}) {
    page.orders[0].column = column;
    page.orders[0].asc = ascending ?? !page.orders[0].asc!;
    _query();
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: SelectDocmentstockDialog(),
      ),
    ).then((v) {
      if (v != null) {
        udtTbDocmentstock = v;
        _query();
      }
    });
  }

  void _fileTransfer(Map<String ,dynamic> map) {
    cryConfirm(context, "是否转移到${map['documentname']}下", (context) async {
      List ids = [];
      dmsfiles.forEach((element) {
        element.documentno=map["documentno"];
        ids.add(int.parse(element.id!));
      });
      DmsFileOdooApi.fileTransfer({"id":ids,"data": {'documentno': map["documentno"],}
      }).then((ResponseBodyApi res) {
        // 对接完善
        if (!res.success!) {
          // CryUtils.message(res.message!);
          return;
        }
        Navigator.pop(context, true);
        CryUtils.message(S.of(context).saved);
      });
    });
  }

  _operationList() {
    return  PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
      ],
    );
  }

}
